// synchronize to period T
1::second => dur T;
T - (now % T) => now;

ConsoleInput in;
// syncing variables
dur tempT;
0 => int newTimeFlag;

// half time
T => T;

SndBuf kick => dac;
"data/kick.wav" => kick.read;
0 => kick.gain;

SndBuf hh => dac;
"data/hihat.wav" => hh.read;
0 => hh.gain;

SndBuf hhopen => dac;
"data/hihat-open.wav" => hhopen.read;
0 => hhopen.gain;

SndBuf snare => dac;
"data/snare-hop.wav" => snare.read;
0 => snare.gain;

fun void play_kick() {
  .3 => kick.gain;

  0 => kick.pos;
  1::T => now;
}

fun void play_hh() {
  .2 => hhopen.gain;
  .2 => hh.gain;

  Std.randf() => float r;
  //  if (r < -0) {
  0 => hhopen.pos;
  .25::T => now;
  0 => hh.pos;
  .25::T => now;
  /*
  } else if (r < 0.5) {
    0 => hhopen.pos;
    .25::T => now;
    0 => hh.pos;
    .125::T => now;
    0 => hh.pos;
    .125::T => now;
  } else {
    0 => hhopen.pos;
    .125::T => now;
    0 => hh.pos;
    .0625::T => now;
    0 => hh.pos;
    .0625::T => now;
    0 => hh.pos;
    .125::T => now;
    0 => hh.pos;
    .125::T => now;
  }
  // */
}

fun void play_snare() {
  .4 => snare.gain;
  0 => snare.pos;
}

fun void read_int() {
  while(true) {
    in.prompt("") => now;
    while (in.more()) {
      in.getLine() => string s;
      Std.atof(s) => float period;
      // set the flag for sync_time
      period::second => tempT; // half-time
      1 => newTimeFlag;
      /*
      if (hz > 0) {// below a certain level doesn't affect
	(1.0/hz) => float period;
	//if (period < 1.0)  // slow down to "half time" if too fast
	//  period * Math.ceil(1/period) => period;
	//else if (period > 2.0) // speed up if too long
	//  period / Math.ceil(period/2) => period;

	// set the flag for sync_time
	period::second => tempT; // half-time
	1 => newTimeFlag;
      }
      */
    }
  }
}

fun void sync_time() {
  // sync time
  if (newTimeFlag) {
    0 => newTimeFlag;
    <<< tempT >>>;
    tempT => T;
  }
}


spork ~ read_int();
while (true) {
  sync_time();

  spork ~ play_kick();
  spork ~ play_hh();
  .5::T => now;

  sync_time();

  spork ~ play_snare();
  spork ~ play_hh();
  .5::T => now;
}
